package com.eaoa.uc.bustransfer.action;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.eaoa.base.EABaseAction;
import com.eaoa.query.bus.BusTransferQuery;
import com.eaoa.uc.busorder.bo.BusOrderSaveBatchBO;
import com.eaoa.vo.bus.BusOrder;
import com.eaoa.vo.bus.BusTransfer;
import com.stony.core.exception.RunException;
import com.stony.core.util.CoreUtils;

public class BusTransferDivideCostAction extends EABaseAction{

	
	@Override
	protected ActionForward doWork(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String result = "Fail";
		
		try {
			
			Long transferno = CoreUtils.parseLong(request.getParameter("transferno")); 
			BusTransfer transfer = BusTransferQuery.loadByNOInitPubOrders(transferno);
			BigDecimal CostTotal = transfer.getCost();
			if(CostTotal==null || CostTotal.floatValue()==0){
				result = "CostZero";
				throw new RunException(result);
			}
			
			Iterator<BusOrder > ordersIt = transfer.getBusOrders().iterator();
			BigDecimal sizeTotal = new BigDecimal(0);
			List<BusOrder> orderList = new ArrayList<BusOrder>();
			while(ordersIt.hasNext() ){
				BusOrder order = (BusOrder)ordersIt.next();
				BigDecimal orderSizeSum = order.getSizesum();
				if(orderSizeSum==null || orderSizeSum.floatValue()==0){
					result = "Order_" +order.getBillcode();
					throw new RunException(result);
				}
				sizeTotal = sizeTotal.add(order.getSizesum());
				orderList.add(order);
			}
			if(sizeTotal==null || sizeTotal.floatValue()==0){
				result = "TotalSizeZero";
				throw new RunException(result);
			}
			
			for(int i=0 ; i<orderList.size(); i++ ){
				BusOrder order = (BusOrder)orderList.get(i);
				BigDecimal orderSizeSum = order.getSizesum();
				BigDecimal right = orderSizeSum.divide(sizeTotal, 8, RoundingMode.HALF_UP);
				BigDecimal myCost = CostTotal.multiply(right).setScale(2, RoundingMode.HALF_UP);
				order.setCost(myCost);				
			}
			
			new BusOrderSaveBatchBO(orderList).execute();
			result = "Success";
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			PrintWriter out = response.getWriter();
			out.write(result);
			out.flush();
			out.close();
		}
		
		return null;
	}
}
